package com.cloud.auth.biz.jwt.base;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

/**
 * @author 王霄
 * @date 2022/6/17 10:30
 */
public class DefaultJwtClient<T> implements JwtClient<T> {
    private final JwtParam jwtParam;
    private final Class<T> clazz;

    public DefaultJwtClient(JwtParam jwtParam, Class<T> clazz) {
        this.jwtParam = jwtParam;
        this.clazz = clazz;
    }

    @Override
    public String generateToken(T payload) {
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(jwtParam.getSecret());
        return JWT.create()
                .withIssuer(jwtParam.getIssuer())
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + jwtParam.getExpire()))
                .withClaim("payload", JSON.toJSONString(payload))
                .sign(algorithm);
    }

    @Override
    public boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(jwtParam.getSecret());
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(jwtParam.getIssuer())
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    public T parseToken(String token) {
        try {
            return JWT.decode(token)
                    .getClaim("payload")
                    .as(clazz);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
